package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 新增菜品和口味
     *
     * @param dto
     */
    @Transactional
    @Override
    public void saveWithFlavor(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //添加菜品
        dishMapper.insert(dish);
        //批量添加关联菜品的口味
        if (dto.getFlavors().size() > 0) {
            for (int i = 0; i < dto.getFlavors().size(); i++) {
                dto.getFlavors().get(i).setDishId(dish.getId());
            }
            dishFlavorMapper.batchInsert(dto.getFlavors());
        }

    }

    @Override
    public PageResult pageQuery(DishPageQueryDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dto);
        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    /**
     * 批量删除商品
     *
     * @param ids
     */
    @Transactional
    @Override
    public void batchDelete(List<Long> ids) {
        //1、正在售卖的商品 不能删
        ids.forEach(id -> {
            Dish dish = dishMapper.queryById(id);
            //正在销售的商品不能删除
            if (dish != null && dish.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });
        //2、有套餐的商品不能删
        List<Long> setmealIds = setmealDishMapper.batchQuerySetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3、批量删除菜品
        dishMapper.batchDeleteByIds(ids);

        //4、批量删除口味
        dishFlavorMapper.batchDeleteByDishIds(ids);


    }


    @Override
    public DishVO queryById(Long id) {
        Dish dish = dishMapper.queryById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        List<DishFlavor> flavors = dishFlavorMapper.queryByDishId(id);
        if (flavors != null && flavors.size() > 0) {
            dishVO.setFlavors(flavors);
        }
        return dishVO;
    }

    @Transactional
    @Override
    public void update(DishDTO dto) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dto, dish);
        //1、修改菜品表
        dishMapper.update(dish);

        //2、删除该菜品的口味表，重新设置新的口味（前端传来的口味）
        List<Long> dishIds = new ArrayList<>();
        dishIds.add(dto.getId());
        //删除原有的口味
        dishFlavorMapper.batchDeleteByDishIds(dishIds);
        if (dto.getFlavors() != null && dto.getFlavors().size() > 0) {
            //批量新增前端传来的口味
            dto.getFlavors().forEach(f -> {
                f.setDishId(dto.getId());
            });
            dishFlavorMapper.batchInsert(dto.getFlavors());
        }


    }

    @Override
    public void enableOrDisable(int status, Long id) {
        Dish dish = Dish.builder().status(status).id(id).build();
        dishMapper.update(dish);
    }

    @Override
    public List<Dish> queryListByCategoryId(Long categoryId) {
        List<Dish> list = dishMapper.queryListByCategoryId(categoryId);
        return list;
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.list(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.queryByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
